<template>
  <el-card class="box-card" :data="articleData" style="min-height: 900px">
    <!-- 文章标题 -->
    <div slot="header" class="clearfix">
      <span style="font-size: 30px">{{ articleData.title }}</span>
      <div style="margin-top:15px">
        <span style="font-size: 15px">{{
          "简介:" + articleData.articleDetails
        }}</span>
      </div>
    </div>
    <!-- 文章内容 -->
    <div style="text-align: left">
      <span
        v-html="articleData.content"
        style="word-break: break-all; word-wrap: break-word"
      >
      </span>
    </div>
    <!-- 文章流量 -->
    <div id="crossline" style="text-align: left">
      <el-divider content-position="left">
        {{ articleData.createdTime }}
      </el-divider>
      <span style="text-align: right; margin-left: 10px">
        <el-button id="dianzan" @click="like(articleData.id)" type="text">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-good"></use>
          </svg>
          {{ goodCount }}</el-button
        >
      </span>

      <span style="text-align: right; margin-left: 10px">
        <el-button type="text">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-comments"></use>
          </svg>
          {{ CommentCount }}</el-button
        >
      </span>
      <span style="text-align: right; margin-left: 10px">
        <el-button type="text" disabled>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-browse"></use>
          </svg>
          {{ viewsCount }}</el-button
        >
      </span>
    </div>
    <!-- 分割线 -->
    <el-divider></el-divider>
    <!-- 评论 -->
    <div style="text-align: left">
      <label style="font-size: 20px"> 评论: </label>
    </div>

    <div style="margin-top: 20px">
      <label style="color: blue"> {{ userName }}: </label>
      <el-input
        style="width: 80%"
        placeholder="文明冲浪，友善评论"
        v-model="toArticleComment"
        clearable
      >
      </el-input>
      <el-button
        style="margin-left: 10px"
        type="primary"
        @click="addComment(toArticleComment)"
        plain
        >发表评论</el-button
      >
    </div>
    <el-divider></el-divider>
    <!-- 评论区 -->
    <div
      style="text-align: left; margin-left: 60px; font-size: 25px"
      v-for="(comment, index) in comData"
      :key="comment.id"
      :index="index"
    >
      <!-- 文章评论 -->
      <div @click="changComment(comment)">
        <div v-if="comment.toCommentId === 0">
          <label style="color: blue">
            {{ comment.commentFormUsername }}:
          </label>
          <div :CommentId="CommentId">
            <span @click="dialogVisible = true" style="cursor: pointer">
              {{ comment.commentConent }}</span
            >
            <div v-if="comment.commentFormUsername !== userName">
              <el-button id="replyBtn" @click="dialogVisible = true" type="text"
                >回复</el-button
              >
            </div>
          </div>
        </div>

        <!-- 回复评论 -->
        <div
          v-for="reply in comData"
          :key="reply.id"
          style="margin-left: 100px; margin-top: 10px; font-size: 15px"
        >
          <div v-if="reply.toCommentId === comment.id">
            <label style="color: blue"
              >{{ reply.commentFormUsername }}&nbsp;&nbsp;回复&nbsp;&nbsp;{{
                reply.commentToUsername
              }}:</label
            >

            <div>
              <span @click="dialogVisible = true" style="cursor: pointer"
                >{{ reply.commentConent }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 回复评论的模态框 -->
    <el-dialog
      title="回复评论"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-input
          placeholder="这么说，你很勇咯？"
          v-model="replyInput"
          clearable
        >
        </el-input
      ></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="(dialogVisible = false), addComment(replyInput, CommentId)"
          >回 复</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  GetCommentMsg,
  getArticlefromId,
  CommentMsg,
  PostLikeMsg,
  ToIdGetLikeCount,
  PostViews,
} from "../../api/index";
import { userlike } from "../../api/like";
// import {CommentMsg} from "../../api/index";

export default {
  props: {
    CommentRecommend: [],
    ViewsRecommend: [],
    AdminRecommend: [],
  },

  watch: {
    CommentRecommend: {
      handler: function(newValue) {
        newValue.forEach((element) => {
          if (element.id === this.articleData.id) {
            this.CommentCount = element.CommentCount;
          }
        });
      },
      deep: true,
    },
    ViewsRecommend: {
      handler: function(newValue) {
        newValue.forEach((element) => {
          if (element.id === this.articleData.id) {
            this.viewsCount = element.viewsCount;
          }
        });
      },
      deep: true,
    },

    articleData: {
      handler: function(newValue, oldValue) {
        // console.log(newValue, oldValue.length === 0);
        if (oldValue.length === 0) {
          this.page();
        }
      },
      deep: true,
    },
    $route: {
      handler: function(newValue, oldValue) {
        console.log(newValue, oldValue);

        this.CommentRecommend.forEach((element) => {
          if (element.id === this.articleData.id) {
            this.CommentCount = element.CommentCount;
          }
        });

        this.ViewsRecommend.forEach((element) => {
          if (element.id === this.articleData.id) {
            this.viewsCount = element.viewsCount;
          }
        });

        this.articleIndex.getArticleId = newValue.query.getArticleId;
        this.getlike(this.articleIndex.getArticleId);
        this.GetUsername();
        this.fetchData();
        this.queryCommentReply();
      },
    },
  },
  data() {
    return {
      CommentCount: 0,
      viewsCount: 0,
      userId: "",
      comData: [],
      goodCount: 0,
      CommentId: 0,
      toArticleComment: "",
      commenter: "session", //评论人，这里会从session拿
      type: 0, //0为评论作者1为评论别人的评论
      byReplier: null, //被评论者的名字
      chosedIndex: -1, //被选中的评论的index
      viewCount: 1,
      comCount: 1,
      likeCount: 1,
      // 用于存放监听到的文章
      articleData: [],

      // 点击标题的索引和id
      articleIndex: {
        getArticleId: -1,
        getIndex: -1,
      },
      // 回复评论的模态框状态
      dialogVisible: false,

      // 回复评论输入框
      replyInput: "",
      userName: "",
    };
  },
  methods: {
    page() {
      var artId = this.articleData.id;
      var userId = localStorage.getItem("userId");
      var res = { UserId: parseInt(userId), ArticleId: artId };
      console.log(res);
      setTimeout(() => {
        PostViews(res)
          .then((data) => {
            console.log(data);
          })
          .catch((err) => {
            console.log(err);
          });
      }, 5000);
    },
    changComment(val) {
      console.log(val);
      this.CommentId = val.id;
    },
    //文章评论
    addComment(data, toCommentId) {
      console.log(data.trim().length > 0);
      if (!data.trim().length > 0) {
        this.$message("评论内容不能为空");
      } else {
        console.log(toCommentId);
        if (!toCommentId) {
          toCommentId = 0;
        }
        var res = {
          ToCommentId: toCommentId,
          Content: data,
          ArticleId: this.articleIndex.getArticleId,
          UserId: parseInt(this.userId),
        };
        console.log(res);
        CommentMsg(res)
          .then((data) => {
            console.log(data);
            this.queryCommentReply();
          })
          .catch((err) => {
            console.log(err);
          });
      }

      this.toArticleComment = "";
    },
    // 点赞方法
    like(id) {
      let dianzan = document.getElementById("dianzan");
      var userid = localStorage.getItem("userId");

      var a = {
        UserId: parseInt(userid),
        ArticleId: id,
      };
      PostLikeMsg(a)
        .then(({ data }) => {
          var res = data.data;
          if (res) {
            this.goodCount += 1;
            dianzan.style.color = "#409EFF";
            console.log("已点赞");
          } else {
            this.goodCount -= 1;
            dianzan.style.color = "black";
            console.log("取消点赞");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //拉取数据
    fetchData() {
      getArticlefromId(this.articleIndex.getArticleId)
        .then(({ data }) => {
          var res = data.data;
          this.articleData = res;
        })
        .catch(({ err }) => {
          console.log(err);
        });
    },

    // 防误触（回复评论模态框）
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },

    //评论渲染数据
    queryCommentReply() {
      //查询评论
      GetCommentMsg(this.articleIndex.getArticleId)
        .then(({ data }) => {
          var res = data.data;
          console.log(res);
          this.comData = res;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    GetUsername() {
      this.userName = localStorage.getItem("userName");
      this.userId = localStorage.getItem("userId");
    },
    getlike() {
      let dianzan = document.getElementById("dianzan");
      var userid = localStorage.getItem("userId");
      var a = {
        UserId: parseInt(userid),
        ArticleId: parseInt(this.articleIndex.getArticleId),
      };
      console.log(a);
      userlike(a)
        .then(({ data }) => {
          var res = data.data;
          if (res) {
            // this.goodCount += 1;
            dianzan.style.color = "#409EFF";
            console.log("已点赞");
          } else {
            // this.goodCount -= 1;
            dianzan.style.color = "black";
            console.log("取消点赞");
          }
        })
        .catch((err) => {
          console.log(err);
        });

      ToIdGetLikeCount(this.articleIndex.getArticleId).then(({ data }) => {
        var res = data.data;
        if (res[0].count) {
          this.goodCount = res[0].count;
        } else {
          this.goodCount = 0;
        }
      });
    },
  },
  mounted() {
    this.articleIndex.getArticleId = this.$route.query.getArticleId - 0;
    this.getlike(this.articleIndex.getArticleId);
    this.GetUsername();
    this.fetchData();
    this.queryCommentReply();
    this.CommentRecommend.forEach((element) => {
      console.log(element.id);
      console.log(this.$route.query.getArticleId);
      if (element.id ===parseInt(this.$route.query.getArticleId)) {
        this.CommentCount = element.CommentCount;
        console.log(this.CommentCount);
      }
    });

    this.ViewsRecommend.forEach((element) => {
      
      if (element.id === parseInt(this.$route.query.getArticleId)) {
        this.viewsCount = element.viewsCount;
        console.log(this.viewsCount);
      }
    });
  },
};
</script>

<style scoped>
.icon {
  width: 25px;
  height: 25px;
  vertical-align: -0.5em;
  fill: currentColor;
  overflow: hidden;
}

.el-button--text {
  color: black;
}

#replyBtn {
  color: #409eff;
  float: right;
  margin-right: 30px;
}
/* .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  } */
</style>
